//
//  PayViewController.m
//  MoodDiary
//
//  Created by X on 2022/1/24.
//

#import "PayViewController.h"
#import "YYLabel.h"

#import <StoreKit/StoreKit.h>
#import "WebUrlViewController.h"


//沙盒测试环境验证
#define SANDBOX     @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore    @"https://buy.itunes.apple.com/verifyReceipt"

@interface PayViewController ()<SKPaymentTransactionObserver,SKProductsRequestDelegate>
{
    UIActivityIndicatorView *_juhua;
    UIView *_payYearView;
    NSString *_payType;
    YYLabel *_titleCenter;
    UIButton * _btnMonth;
    YYLabel *_btnLable;
}
@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _payType=@"0";
    
    UIButton *btnCannel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCannel.frame = CGRectMake(KW(18), DEF_StatusBarAndNavigationBarHeight-KW(40), KW(40), KW(40));
    btnCannel.backgroundColor = [UIColor clearColor];
    [btnCannel setBackgroundImage:[UIImage imageNamed:@"payNo"] forState:UIControlStateNormal];
    [[btnCannel rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:^{}];
    }];
    [self.view addSubview:btnCannel];
    
    [self checkOrderStatus];
    
    [self showView];
    
    _juhua = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _juhua.center = self.view.center;
    _juhua.backgroundColor = [UIColor clearColor];
    _juhua.alpha = 0.5;
    [self.view addSubview:_juhua];
    
    [self data];
    // Do any additional setup after loading the view.
}

-(void)data{
    [self->_juhua startAnimating];
    _payType=@"0";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self->_juhua stopAnimating];
       // 需要延迟执行的代码
    });
    if ([SKPaymentQueue canMakePayments]) {
        // 如果允许应用内付费购买
//            [ANCustomHUD showLoadingText:@"正在拉起苹果内购" View:nil];
//        [self->_juhua startAnimating];
        // 把商品ID信息放入一个集合中
        NSSet * set = [NSSet setWithArray:@[@"moodDiary293",@"moodDiary73"]];
        // 请求内购商品信息，只返回你请求的产品（主要用于验证商品的有效性）
        SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
        request.delegate = self;
        [request start];
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self->_juhua stopAnimating];
//           // 需要延迟执行的代码
//        });
        
    } else {
        // 如果用户手机禁止应用内付费购买.
        // 则弹出开启购买权限开关的提示等...
    }
}

/** 检测客户端与服务器漏单情况处理*/
- (void)checkOrderStatus
{
    NSDictionary *orderInfo = [self getReceiptData];
    if (orderInfo != nil) {
        
        NSString *orderId = orderInfo[@"userID"];
        NSString *receipt = orderInfo[@"receipt"];
        
        if ([@"123456789" isEqualToString:orderId]) {
            [self appVerificationReceipt:receipt];
        }
    }
}

-(void)showView{
    UIButton * btnPayBack = [UIButton buttonWithType:UIButtonTypeCustom];
    btnPayBack.frame = CGRectMake(SCREEN_WIDTH-KW(80)-KW(10), DEF_StatusBarAndNavigationBarHeight-KW(40), KW(80), KW(40));
    btnPayBack.backgroundColor = [UIColor whiteColor];
    btnPayBack.clipsToBounds=YES;
    [btnPayBack setTitle:@"恢复订阅" forState:UIControlStateNormal];
    [btnPayBack setTitleColor:COLOR(27, 97, 238, 1) forState:UIControlStateNormal];
    btnPayBack.titleLabel.font = [UIFont systemFontOfSize:KW(14)];
    [[btnPayBack rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self->_juhua startAnimating];
        [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }];
    [self.view addSubview:btnPayBack];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0,DEF_StatusBarAndNavigationBarHeight +KW(10), SCREEN_WIDTH, KW(30))];
    title.font = [UIFont systemFontOfSize:KW(22)];
    title.textColor=[UIColor blackColor];
    title.textAlignment = NSTextAlignmentCenter;
    title.text=@"完全使用产品";
    [self.view addSubview:title];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-KW(335))/2, CGRectGetMaxY(title.frame)+KW(26), KW(335), KW(323))];
    backView.backgroundColor = [UIColor whiteColor];
    backView.layer.cornerRadius = KW(10);
    backView.layer.borderColor = COLOR(216, 216, 216, 1).CGColor;
    backView.layer.borderWidth = 0.5;
    [self.view addSubview:backView];
    
    UIImageView * emo = [[UIImageView alloc] initWithFrame:CGRectMake((KW(335)-KW(140))/2, KW(44),KW(140), KW(80))];
    emo.image = [UIImage imageNamed:@"payEmo"];
    [backView addSubview:emo];
    
    _titleCenter = [[YYLabel alloc] init];
    [backView addSubview:_titleCenter];
    
    NSMutableAttributedString *contentAttributedString;
    
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] != nil) {
        contentAttributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]]];
        contentAttributedString.yy_font = [UIFont systemFontOfSize:KW(12)];
        contentAttributedString.yy_lineSpacing = KW(1);
        contentAttributedString.yy_color = COLOR(102, 102, 102, 1);
        contentAttributedString.yy_alignment=NSTextAlignmentCenter;
        [contentAttributedString yy_setTextHighlightRange:[[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/年",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]]]
                                                    color:COLOR(28, 153, 255, 1)
                                          backgroundColor:nil
                                                tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                }];
        [contentAttributedString yy_setFont:[UIFont fontWithName:@"Helvetica-Bold" size:KW(14)] range:[[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/年",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]]]];
    }else{
        _titleCenter.text=@"7天试用期过后，以¥--/年价格自动续订";
    }
    _titleCenter.frame=CGRectMake(0,CGRectGetMaxY(emo.frame)+KW(20), KW(335), KW(17));
    _titleCenter.attributedText =contentAttributedString;
    
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(KW(13),KW(181), KW(335)-KW(26), 0.5)];
    lineView.backgroundColor=COLOR(216, 216, 216, 1);
//    [self drawDashLine:lineView lineLength:KW(335)-KW(26) lineSpacing:KW(2) lineColor:COLOR(216, 216, 216, 1)];
    [backView addSubview:lineView];
    
    UIImageView * payImage1 = [[UIImageView alloc] initWithFrame:CGRectMake(KW(13), CGRectGetMaxY(_titleCenter.frame)+KW(40),KW(20), KW(20))];
    payImage1.image = [UIImage imageNamed:@"payimage3"];
    [backView addSubview:payImage1];
    
    UILabel *titleLab1 = [[UILabel alloc] initWithFrame:CGRectMake(KW(42),CGRectGetMaxY(_titleCenter.frame)+KW(42), KW(200), KW(17))];
    titleLab1.font = [UIFont systemFontOfSize:KW(12)];
    titleLab1.textColor=COLOR(164, 164, 164, 1);
    titleLab1.textAlignment = NSTextAlignmentLeft;
    titleLab1.text=@"丰富多样的心情情绪选择";
    [backView addSubview:titleLab1];
    
    UIImageView * payImage2 = [[UIImageView alloc] initWithFrame:CGRectMake(KW(13), CGRectGetMaxY(payImage1.frame)+KW(20),KW(20), KW(20))];
    payImage2.image = [UIImage imageNamed:@"payimage2"];
    [backView addSubview:payImage2];
    
    UILabel *titleLab2 = [[UILabel alloc] initWithFrame:CGRectMake(KW(42),CGRectGetMaxY(titleLab1.frame)+KW(24), KW(200), KW(17))];
    titleLab2.font = [UIFont systemFontOfSize:KW(12)];
    titleLab2.textColor=COLOR(164, 164, 164, 1);
    titleLab2.textAlignment = NSTextAlignmentLeft;
    titleLab2.text=@"记录天气和好心情";
    [backView addSubview:titleLab2];
    
    UIImageView * payImage3 = [[UIImageView alloc] initWithFrame:CGRectMake(KW(13), CGRectGetMaxY(payImage2.frame)+KW(20),KW(20), KW(20))];
    payImage3.image = [UIImage imageNamed:@"payimage1"];
    [backView addSubview:payImage3];
    
    UILabel *titleLab3 = [[UILabel alloc] initWithFrame:CGRectMake(KW(42),CGRectGetMaxY(titleLab2.frame)+KW(24), KW(200), KW(17))];
    titleLab3.font = [UIFont systemFontOfSize:KW(12)];
    titleLab3.textColor=COLOR(164, 164, 164, 1);
    titleLab3.textAlignment = NSTextAlignmentLeft;
    titleLab3.text=@"满满的心情统计";
    [backView addSubview:titleLab3];
    
    
    UIButton * btnLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    btnLogin.frame = CGRectMake(KW(20), CGRectGetMaxY(backView.frame)+KW(20), SCREEN_WIDTH-KW(40), KW(60));
    btnLogin.backgroundColor = COLOR(26, 26, 26, 1);
    btnLogin.layer.cornerRadius = KW(10);
    btnLogin.clipsToBounds=YES;
    [btnLogin setTitle:@"试用7天，按年订阅" forState:UIControlStateNormal];
    [btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnLogin.titleLabel.font = [UIFont systemFontOfSize:KW(16)];
    [[btnLogin rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self showYearV];
    }];
    [self.view addSubview:btnLogin];
    
    _btnMonth = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnMonth.frame = CGRectMake(KW(20), CGRectGetMaxY(btnLogin.frame)+KW(20), SCREEN_WIDTH-KW(40), KW(60));
    _btnMonth.backgroundColor = [UIColor whiteColor];
    _btnMonth.layer.cornerRadius = KW(10);
    _btnMonth.clipsToBounds=YES;
    [_btnMonth setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _btnMonth.titleLabel.font = [UIFont systemFontOfSize:KW(16)];
    _btnMonth.layer.borderColor = [UIColor blackColor].CGColor;
    _btnMonth.layer.borderWidth = 0.5;
    [[_btnMonth rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        self->_payType=@"1";
        if ([SKPaymentQueue canMakePayments]) {
            // 如果允许应用内付费购买
//            [ANCustomHUD showLoadingText:@"正在拉起苹果内购" View:nil];
            [self->_juhua startAnimating];
            // 把商品ID信息放入一个集合中
            NSSet * set = [NSSet setWithArray:@[@"moodDiary73"]];
            // 请求内购商品信息，只返回你请求的产品（主要用于验证商品的有效性）
            SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
            request.delegate = self;
            [request start];
        } else {
            // 如果用户手机禁止应用内付费购买.
            // 则弹出开启购买权限开关的提示等...
        }
    }];
    [self.view addSubview:_btnMonth];
    
    _btnLable = [[YYLabel alloc] init];
    [_btnMonth addSubview:_btnLable];
    
    NSMutableAttributedString *contentAttributedStringbtn;
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"monthPrice"] != nil) {
        contentAttributedStringbtn = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"每月订阅！¥%.2f/月",[[[NSUserDefaults standardUserDefaults] valueForKey:@"monthPrice"] floatValue]]];
        contentAttributedStringbtn.yy_font = [UIFont systemFontOfSize:KW(16)];
        contentAttributedStringbtn.yy_lineSpacing = KW(1);
        contentAttributedStringbtn.yy_color = COLOR(1, 1, 1, 1);
        contentAttributedStringbtn.yy_alignment=NSTextAlignmentCenter;
        [contentAttributedStringbtn yy_setTextHighlightRange:[[NSString stringWithFormat:@"每月订阅！¥%.2f/月",[[[NSUserDefaults standardUserDefaults] valueForKey:@"monthPrice"] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/月",[[[NSUserDefaults standardUserDefaults] valueForKey:@"monthPrice"] floatValue]]]
                                                    color:COLOR(28, 153, 255, 1)
                                          backgroundColor:nil
                                                tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                }];
        [contentAttributedStringbtn yy_setFont:[UIFont fontWithName:@"Helvetica-Bold" size:KW(18)] range:[[NSString stringWithFormat:@"每月订阅！¥%.2f/月",[[[NSUserDefaults standardUserDefaults] valueForKey:@"monthPrice"] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/月",[[[NSUserDefaults standardUserDefaults] valueForKey:@"monthPrice"] floatValue]]]];
    }else{
        _btnLable.text=@"每月订阅！¥--/月";
    }
    _btnLable.frame=CGRectMake(0,0,_btnMonth.width, _btnMonth.height);
    _btnLable.attributedText =contentAttributedStringbtn;
    
    YYLabel *labNum = [[YYLabel alloc] init];
    labNum.numberOfLines = 0;
    [self.view addSubview:labNum];
    labNum.frame=CGRectMake(KW(20), CGRectGetMaxY(_btnMonth.frame)+KW(10), SCREEN_WIDTH-KW(40), KW(100));
    
    NSMutableAttributedString *contentAttributedString1 = [[NSMutableAttributedString alloc] initWithString:@"您的按年订阅包括免费试用期，免费试用期在您的 iTunes 帐户确认购买后开始。试用期结束后，您的订阅将自动开始和续订。除非您在当期结束前至少24小时在您的账户设置中禁用自动续订或取消您的订阅，否则您的 iTunes 账户将收取下期费用。有关条款请参阅《用户协议》及《隐私政策》"];
    contentAttributedString1.yy_font = [UIFont systemFontOfSize:KW(12)];
    contentAttributedString1.yy_lineSpacing = KW(5);
    contentAttributedString1.yy_color = [UIColor blackColor];
    contentAttributedString1.yy_alignment=NSTextAlignmentCenter;
    
    NSRange range1=[[contentAttributedString1 string]rangeOfString:@"用户协议" ];
    YYTextDecoration* deco=[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:1] color:[UIColor blackColor]];
    [contentAttributedString1 yy_setTextUnderline:deco range:range1];
    
    NSRange range2=[[contentAttributedString1 string]rangeOfString:@"隐私政策" ];
    YYTextDecoration* deco2=[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:1] color:[UIColor blackColor]];
    [contentAttributedString1 yy_setTextUnderline:deco2 range:range2];
    
    [contentAttributedString1 yy_setTextHighlightRange:[@"您的按年订阅包括免费试用期，免费试用期在您的 iTunes 帐户确认购买后开始。试用期结束后，您的订阅将自动开始和续订。除非您在当期结束前至少24小时在您的账户设置中禁用自动续订或取消您的订阅，否则您的 iTunes 账户将收取下期费用。有关条款请参阅《用户协议》及《隐私政策》" rangeOfString:@"《用户协议》"]
                                                color:[UIColor blackColor]
                                      backgroundColor:nil
                                            tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
        WebUrlViewController *loginController = [[WebUrlViewController alloc]init];
        //新建导航控制器，解决model页面无法使用push
        UINavigationController *loginNavigation = [[UINavigationController alloc]initWithRootViewController:loginController];
        loginController.webUrlType=WebUrlTypeYonghuxieyi;
//        loginNavigation.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:loginNavigation animated:NO completion:^{}];
                                            }];
    [contentAttributedString1 yy_setTextHighlightRange:[@"您的按年订阅包括免费试用期，免费试用期在您的 iTunes 帐户确认购买后开始。试用期结束后，您的订阅将自动开始和续订。除非您在当期结束前至少24小时在您的账户设置中禁用自动续订或取消您的订阅，否则您的 iTunes 账户将收取下期费用。有关条款请参阅《用户协议》及《隐私政策》" rangeOfString:@"《隐私政策》"]
                                                color:[UIColor blackColor]
                                      backgroundColor:nil
                                            tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
        WebUrlViewController *loginController = [[WebUrlViewController alloc]init];
        //新建导航控制器，解决model页面无法使用push
        UINavigationController *loginNavigation = [[UINavigationController alloc]initWithRootViewController:loginController];
//        loginNavigation.modalPresentationStyle = UIModalPresentationFullScreen;
        loginController.webUrlType=WebUrlTypeYinsizhengce;
        [self presentViewController:loginNavigation animated:NO completion:^{}];
                                            }];
    
    labNum.attributedText =contentAttributedString1;
}

//获取请求完成和失败的结果
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [self->_juhua stopAnimating];
    NSLog(@"------------------错误-----------------:%@", error);
}
- (void)requestDidFinish:(SKRequest *)request{
    NSLog(@"------------反馈信息结束-----------------");
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response NS_AVAILABLE(10_7, 3_0); {
//    [ANCustomHUD hiddenLoadingView:nil];
    NSLog(@"--------------收到产品反馈消息---------------------");
    NSArray *product = response.products;
    if([product count] == 0){
        NSLog(@"--------------没有商品------------------");
        return;
    }
    NSLog(@"productID:%@", response.invalidProductIdentifiers);
    NSLog(@"产品付费数量:%lu",(unsigned long)[product count]);
    
    if ([_payType integerValue] == 0) {
        [self->_juhua stopAnimating];
        for (int i  =0;i <product.count;i++) {
            SKProduct *pro =[SKProduct new];
            pro=product[i];
            NSLog(@"%@", [pro description]);
            NSLog(@"%@", [pro localizedTitle]);
            NSLog(@"%@", [pro localizedDescription]);
            NSLog(@"++++%@", [pro price]);
            NSLog(@"%@", [pro productIdentifier]);
            if (i ==0) {
                NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[pro price] floatValue]]];
                contentAttributedString.yy_font = [UIFont systemFontOfSize:KW(12)];
                contentAttributedString.yy_lineSpacing = KW(1);
                contentAttributedString.yy_color = COLOR(102, 102, 102, 1);
                contentAttributedString.yy_alignment=NSTextAlignmentCenter;
                [contentAttributedString yy_setTextHighlightRange:[[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[pro price] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/年",[[pro price] floatValue]]]
                                                            color:COLOR(28, 153, 255, 1)
                                                  backgroundColor:nil
                                                        tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                        }];
                [contentAttributedString yy_setFont:[UIFont fontWithName:@"Helvetica-Bold" size:KW(14)] range:[[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[pro price] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/年",[[pro price] floatValue]]]];
            _titleCenter.attributedText =contentAttributedString;
                [[NSUserDefaults standardUserDefaults] setValue:[pro price] forKey:@"yearPrice"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }else if(i == 1){
                NSMutableAttributedString *  contentAttributedStringbtn = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"每月订阅！¥%.2f/月",[[pro price] floatValue]]];
                    contentAttributedStringbtn.yy_font = [UIFont systemFontOfSize:KW(16)];
                    contentAttributedStringbtn.yy_lineSpacing = KW(1);
                    contentAttributedStringbtn.yy_color = COLOR(1, 1, 1, 1);
                    contentAttributedStringbtn.yy_alignment=NSTextAlignmentCenter;
                    [contentAttributedStringbtn yy_setTextHighlightRange:[[NSString stringWithFormat:@"每月订阅！¥%.2f/月",[[pro price] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/月",[[pro price] floatValue]]]
                                                                color:COLOR(28, 153, 255, 1)
                                                      backgroundColor:nil
                                                            tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                            }];
                [contentAttributedStringbtn yy_setFont:[UIFont fontWithName:@"Helvetica-Bold" size:KW(18)] range:[[NSString stringWithFormat:@"每月订阅！¥%.2f/月",[[pro price] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/月",[[pro price] floatValue]]]];
                _btnLable.attributedText =contentAttributedStringbtn;
                [[NSUserDefaults standardUserDefaults] setValue:[pro price] forKey:@"monthPrice"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
    }else{
        SKProduct *p = product.lastObject;
//        [self->_juhua startAnimating];
        ///发送购买请求，创建支付
        SKPayment *payment = [SKPayment paymentWithProduct:p];
        //提交付款申请
        [[SKPaymentQueue defaultQueue] addPayment:payment];
        //支付运行时，一定要添加监听
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions NS_AVAILABLE(10_7, 3_0);
{
    for(SKPaymentTransaction *tran in transactions){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
            {  ///交易完成。事务在队列中，用户已被收费。更新UI以反映正在进行的状态，并等待再次调用。
                NSLog(@"交易完成");
                [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"payStatus"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self verifyPurchaseWithPaymentTransaction:tran ];
                [self finishTransactionTask:tran];
            }
                break;
            case SKPaymentTransactionStatePurchasing:
            {   //商品添加进列表，事物被添加到服务器队列中。提供购买的功能
                NSLog(@"商品添加进列表");
            }
                break;
            case SKPaymentTransactionStateRestored:
            {//事务从用户的购买历史记录中恢复。恢复以前购买的功能。
                NSLog(@"已经购买过商品");
                [self finishTransactionTask:tran];
            }
                break;
            case SKPaymentTransactionStateFailed:
            { //交易失败，购买失败或者用户取消。使用error属性的值向用户显示消息。
//                [ANCustomHUD showError:@"购买失败" toView:nil];
                [self finishTransactionTask:tran];
            }
                break;
            case SKPaymentTransactionStateDeferred: {//未知状态。更新UI以反映延迟状态，并等待再次调用。
//                [ANCustomHUD showError:@"最终状态未确定" toView:nil];
                [self finishTransactionTask:tran];
            }
                break;
            default:
                break;
        }
    }
}

/**
 *  验证购买，避免越狱软件模拟苹果请求达到非法购买问题
 票据的校验是保证内购安全完成的非常关键的一步，一般有三种方式：
 1、服务器验证，获取票据信息后上传至信任的服务器，由服务器完成与App Store的验证（提倡使用此方法，比较安全）
 2、本地票据校验
 3、本地App Store请求验证
 *
 */
-(void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction{
    ///解除监听
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    if (!receiptData) {
        return  ;
    }
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:0];//转化为base64字符串
    NSLog(@"内购完成的收据为：%@",receiptString);
    [self saveReceiptData:@{@"receipt":receiptString,
                            @"userID":@"123456789"}];
    [self appVerificationReceipt:receiptString];
    

}
///APP直接去苹果服务器验证
- (void)appVerificationReceipt:(NSString *)receiptString {
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\", \"password\" : \"%@\"}", receiptString,@"8aa12c81702b4ddd8668753de2fb2403"];//拼接请求数据
//    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:AppStore];
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody = bodyData;
    requestM.HTTPMethod = @"POST";
    
    // 创建连接并发送同步请求
    NSError *error = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error];
    if (error) {
        NSLog(@"验证购买过程中发生错误，错误信息：%@",error.localizedDescription);
        return;
    }
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",dic);
    if ([dic[@"status"] intValue]==0) {
        NSLog(@"购买成功!");

        ///解除监听
        [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
        [self removeLocReceiptData];
    } else {
        
    }
}
//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"交易结束");
    [self finishTransactionTask:transaction];
}
///完成交易：完成交易前需要完成：坚持购买 或  下载相关内容  或 更新应用的UI以允许用户访问产品
- (void)finishTransactionTask:(SKPaymentTransaction *)transaction   {
    ///从队列中删除已完成(即失败或已完成)的事务。试图完成购买事务将引发异常。
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

    [[NSUserDefaults standardUserDefaults] setValue:@"2" forKey:@"group.com.moodDiary.StartState"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self dismissViewControllerAnimated:YES completion:^{
        [self->_juhua stopAnimating];
    }];
}
- (void)dealloc{
    ///解除监听
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

#pragma mark -- 本地保存一次支付凭证
static NSString *const kSaveReceiptData = @"kSaveReceiptData";

- (void)saveReceiptData:(NSDictionary *)receiptData
{
    [[NSUserDefaults standardUserDefaults] setValue:receiptData forKey:kSaveReceiptData];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSDictionary *)getReceiptData
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:kSaveReceiptData];
}

- (void)removeLocReceiptData
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSaveReceiptData];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)showYearV{
    _payYearView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _payYearView.backgroundColor=COLOR(0, 0, 0, 0.7);
    [self.view addSubview:_payYearView];
    
    UIView *yearV1=[[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-KW(324), SCREEN_WIDTH, KW(340))];
    yearV1.backgroundColor=[UIColor whiteColor];
    yearV1.layer.cornerRadius = KW(20);
    [_payYearView addSubview:yearV1];
    
    UIButton *btnCannel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCannel.frame = CGRectMake(SCREEN_WIDTH-KW(40), 0, KW(40), KW(40));
    btnCannel.backgroundColor = [UIColor clearColor];
    btnCannel.layer.cornerRadius = KW(20);
    btnCannel.clipsToBounds=YES;
    [btnCannel setBackgroundImage:[UIImage imageNamed:@"payNo"] forState:UIControlStateNormal];
    [[btnCannel rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self->_payYearView removeFromSuperview];
    }];
    [yearV1 addSubview:btnCannel];
    
    UIImageView * emo = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-KW(80))/2, -KW(40),KW(80), KW(80))];
    emo.image = [UIImage imageNamed:@"payVIcon"];
    [yearV1 addSubview:emo];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(emo.frame)+KW(20), SCREEN_WIDTH, KW(25))];
    title.font = [UIFont systemFontOfSize:KW(18)];
    title.textColor=[UIColor blackColor];
    title.textAlignment = NSTextAlignmentCenter;
    title.text=@"请确认您的订阅信息";
    [yearV1 addSubview:title];
    
    YYLabel *labNum = [[YYLabel alloc] init];
    labNum.numberOfLines = 0;
    [yearV1 addSubview:labNum];
    labNum.frame=CGRectMake(KW(20), CGRectGetMaxY(title.frame)+KW(30), SCREEN_WIDTH-KW(40), KW(44));
    NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订\n可以随时取消订阅",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]]];
    contentAttributedString.yy_font = [UIFont systemFontOfSize:KW(14)];
    contentAttributedString.yy_lineSpacing = KW(4);
    contentAttributedString.yy_color = [UIColor blackColor];
    contentAttributedString.yy_alignment=NSTextAlignmentCenter;
    [contentAttributedString yy_setTextHighlightRange:[[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/年",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]]]
                                                color:COLOR(28, 153, 255, 1)
                                      backgroundColor:nil
                                            tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                            }];
    [contentAttributedString yy_setFont:[UIFont fontWithName:@"Helvetica-Bold" size:KW(16)] range:[[NSString stringWithFormat:@"7天试用期过后，以¥%.2f/年价格自动续订",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]] rangeOfString:[NSString stringWithFormat:@"¥%.2f/年",[[[NSUserDefaults standardUserDefaults] valueForKey:@"yearPrice"] floatValue]]]];
    labNum.attributedText =contentAttributedString;

    UIButton * btnLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    btnLogin.frame = CGRectMake(KW(20), CGRectGetMaxY(labNum.frame)+KW(33), SCREEN_WIDTH-KW(40), KW(60));
    btnLogin.backgroundColor = COLOR(26, 26, 26, 1);
    btnLogin.layer.cornerRadius = KW(10);
    btnLogin.clipsToBounds=YES;
    [btnLogin setTitle:@"开始试用" forState:UIControlStateNormal];
    [btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnLogin.titleLabel.font = [UIFont systemFontOfSize:KW(16)];
    [[btnLogin rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        self->_payType=@"1";
        if ([SKPaymentQueue canMakePayments]) {
            // 如果允许应用内付费购买
//            [ANCustomHUD showLoadingText:@"正在拉起苹果内购" View:nil];
            [self->_juhua startAnimating];
            // 把商品ID信息放入一个集合中
            NSSet * set = [NSSet setWithArray:@[@"moodDiary293"]];
            // 请求内购商品信息，只返回你请求的产品（主要用于验证商品的有效性）
            SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
            request.delegate = self;
            [request start];
        } else {
            // 如果用户手机禁止应用内付费购买.
            // 则弹出开启购买权限开关的提示等...
        }
    }];
    [yearV1 addSubview:btnLogin];
    
    UIButton * btnOut = [UIButton buttonWithType:UIButtonTypeCustom];
    btnOut.frame = CGRectMake(KW(20), CGRectGetMaxY(btnLogin.frame), SCREEN_WIDTH-KW(40), KW(60));
    btnOut.backgroundColor = [UIColor whiteColor];
    btnOut.clipsToBounds=YES;
    [btnOut setTitle:@"暂时不用" forState:UIControlStateNormal];
    [btnOut setTitleColor:COLOR(131, 131, 131, 1) forState:UIControlStateNormal];
    btnOut.titleLabel.font = [UIFont systemFontOfSize:KW(16)];
    [[btnOut rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:^{}];
    }];
    [yearV1 addSubview:btnOut];
}

//-(void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor{
//
//CGRect rect = CGRectMake(0, 0, CGRectGetWidth(lineView.frame), CGRectGetHeight(lineView.frame));
//CGSize radii = CGSizeMake(5, 5);//圆角
//UIRectCorner corners = UIRectCornerAllCorners;
////create path
//UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:radii];
////create shape layer
//CAShapeLayer *shapeLayer = [CAShapeLayer layer];
//shapeLayer.strokeColor = lineColor.CGColor;
//shapeLayer.fillColor = [UIColor clearColor].CGColor;
//shapeLayer.lineWidth = KW(1);//line的高度
//shapeLayer.lineJoin = kCALineJoinRound;
//shapeLayer.lineCap = kCALineCapRound;
//shapeLayer.path = path.CGPath;
//shapeLayer.lineDashPattern = @[[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing]];//画虚线(虚线宽、虚线间隔)
////add it to our view
//[lineView.layer addSublayer:shapeLayer];
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
